package com.dataseek.iot.toolikit.common.service;

import com.dataseek.iot.toolikit.common.util.HashUtil;
import com.github.yitter.contract.IIdGenerator;
import com.github.yitter.contract.IdGeneratorOptions;
import com.github.yitter.idgen.DefaultIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.util.Random;
//新款雪花ID分布式生成器
@Service
@Slf4j
public class IDServiceHelper implements InitializingBean {
    private IIdGenerator iIdGenerator;

    @Value("${dubbo.application.name}")
    private String applicationName;

    @Override
    public void afterPropertiesSet() throws Exception {
        Random rand = new Random();
        short workerid = (short) ((rand.nextInt(16))& 0xf);
        try{
            workerid = fetchWorkid();
        }
        catch (Exception ex){
            log.error(ex.getMessage());
        }
        IdGeneratorOptions options = new IdGeneratorOptions(workerid);
        options.WorkerIdBitLength = 10;
        iIdGenerator = new DefaultIdGenerator(options);
    }

    public Long nextId(){
        return iIdGenerator.newLong();
    }

    private short fetchWorkid(){
        int hashInt = HashUtil.bernstein(applicationName)& 0xf;
        short hashShort=((short)hashInt);
        return hashShort;
    }
}
